/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ArticleEditor.StartMenu.actions;

import java.awt.Color;
import java.awt.Component;
import java.awt.GraphicsEnvironment;
import java.awt.ItemSelectable;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.font.TextAttribute;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.AttributedString;
import java.util.Collection;
import javax.swing.JComboBox;
import javax.swing.JTextPane;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.ArticleEditor.StartMenu.Font;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.articleEditor.view.Styleable;
import org.articleEditor.articleKit.DocxEditorKit;
import org.openide.loaders.DataObject;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.Utilities;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//org.ArticleEditor.StartMenu.actions//windows//EN",
        autostore = false
)
@TopComponent.Description(
        preferredID = "windowsTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(mode = "bottomSlidingSide", openAtStartup = true)
@ActionID(category = "Window", id = "org.ArticleEditor.StartMenu.actions.windowsTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_windowsAction",
        preferredID = "windowsTopComponent"
)
@Messages({
    "CTL_windowsAction=windows",
    "CTL_windowsTopComponent=windows Window",
    "HINT_windowsTopComponent=This is a windows window"
})
public final class windowsTopComponent extends TopComponent implements LookupListener{

    DataObject Dobj;
    private Styleable styleable;
    private Lookup.Result<DataObject> result = null;
    private Lookup.Result<Styleable> resultStyle = null;
    private JTextPane textPane;
    boolean bandera=false;
    Color colorfondodefault;
    Highlighter hilit;
    Highlighter.HighlightPainter painter;
    
    public windowsTopComponent() {
        initComponents();
        
        setName(Bundle.CTL_windowsTopComponent());
        setToolTipText(Bundle.HINT_windowsTopComponent());
        SetFonts();
        SetSizeFonts();
        Dobj = null;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        namesFont = new javax.swing.JComboBox();
        sizeFont = new javax.swing.JComboBox();
        Buscar = new javax.swing.JTextField();
        estado = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        namesFont.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        namesFont.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                namesFontMouseMoved(evt);
            }
        });
        namesFont.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                namesFontActionPerformed(evt);
            }
        });
        namesFont.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                namesFontKeyPressed(evt);
            }
        });

        sizeFont.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        sizeFont.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                sizeFontMouseMoved(evt);
            }
        });
        sizeFont.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sizeFontActionPerformed(evt);
            }
        });
        sizeFont.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                sizeFontKeyPressed(evt);
            }
        });

        Buscar.setText(org.openide.util.NbBundle.getMessage(windowsTopComponent.class, "windowsTopComponent.Buscar.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(estado, org.openide.util.NbBundle.getMessage(windowsTopComponent.class, "windowsTopComponent.estado.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jButton1, org.openide.util.NbBundle.getMessage(windowsTopComponent.class, "windowsTopComponent.jButton1.text")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jButton2, org.openide.util.NbBundle.getMessage(windowsTopComponent.class, "windowsTopComponent.jButton2.text")); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGap(42, 42, 42)
                        .addComponent(jButton2))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(namesFont, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(42, 42, 42)
                        .addComponent(sizeFont, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(55, 55, 55)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(estado)
                            .addComponent(Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(65, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(namesFont, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(sizeFont, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(estado)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(40, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    
    private void listenerBuscar()
    {
        hilit = new DefaultHighlighter();
        painter = new DefaultHighlighter.DefaultHighlightPainter(Color.CYAN);
        textPane.setHighlighter(hilit);
        colorfondodefault = Buscar.getBackground();
        Buscar.addKeyListener(new KeyListener(){
            
            @Override
            public void keyPressed(KeyEvent e) {
             if(e.getKeyCode()==KeyEvent.VK_ESCAPE){
              hilit.removeAllHighlights();
                       Buscar.setText("");
                       Buscar.setBackground(colorfondodefault);
             }
            }

            @Override
            public void keyReleased(KeyEvent e) {
             // TODO Auto-generated method stub
             searchText();
            }   
            
            @Override
            public void keyTyped(KeyEvent e) {
               }
        });
    }
    
    
    public void searchText() {
     
        hilit.removeAllHighlights();
        String s = Buscar.getText();
        
        if (s.length() > 0) {           
         String contenido = textPane.getText();
            int index = contenido.indexOf(s, 0);
            if (index >= 0) {
                try {
                    int end = index + s.length();
                    hilit.addHighlight(index, end, painter);
                    textPane.setCaretPosition(end);
                    Buscar.setBackground(colorfondodefault);
                    estado.setText("'" + s + "' fue encontrado. Presione ESC para finalizar la busqueda.");
                } catch (BadLocationException e) {
                    e.printStackTrace();
                }
            } else {
                Buscar.setBackground(Color.ORANGE);
                estado.setText("'" + s + "' no se ha encontrado. Presione ESC para finalizar la busqueda.");
            }
        }else{
         estado.setText("Digite la palabra a buscar.");
        }
    }
    
    private void namesFontActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_namesFontActionPerformed
   
        if ( bandera==true)
        {
            String fontName=(String) namesFont.getSelectedItem();
            AttributedString attributes = new AttributedString("ChangeFont");
            if (fontName != null && styleable!=null) {           
             attributes.addAttribute(TextAttribute.FAMILY, fontName);
             styleable.setFontAttributes(attributes);
            }  
        }
    }//GEN-LAST:event_namesFontActionPerformed

    private void namesFontKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_namesFontKeyPressed
       if(evt.getKeyCode() == KeyEvent.VK_ENTER)
       {
           String fontName=(String) namesFont.getSelectedItem();
           AttributedString attributes = new AttributedString("ChangeFont");
           if (fontName != null && styleable!=null) {           
            attributes.addAttribute(TextAttribute.FAMILY, fontName);
            styleable.setFontAttributes(attributes);
        }
       }
    }//GEN-LAST:event_namesFontKeyPressed

    private void sizeFontActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sizeFontActionPerformed
        
        if ( bandera==true)
        {
           String tam= (String)sizeFont.getSelectedItem();
           AttributedString attributes = new AttributedString("FontSize");
           if (tam != null && styleable!=null) {  
            Integer num=new Integer(Integer.parseInt(tam));
            Number number=(Number)num;
           attributes.addAttribute(TextAttribute.SIZE, number);
           styleable.setFontAttributes(attributes);
           }
        }        
    }//GEN-LAST:event_sizeFontActionPerformed

    private void sizeFontKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_sizeFontKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER)
       {
           String tam= (String)sizeFont.getSelectedItem();
           AttributedString attributes = new AttributedString("FontSize");
           if (tam != null && styleable!=null) {           
           Integer num=new Integer(Integer.parseInt(tam));
           Number number=(Number)num;
           attributes.addAttribute(TextAttribute.SIZE, number);
            styleable.setFontAttributes(attributes);
        }
       }
    }//GEN-LAST:event_sizeFontKeyPressed

    private void namesFontMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_namesFontMouseMoved
       bandera=true;
    }//GEN-LAST:event_namesFontMouseMoved

    private void sizeFontMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sizeFontMouseMoved
        bandera=true;
    }//GEN-LAST:event_sizeFontMouseMoved

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    
        DocxEditorKit j=new DocxEditorKit();       
        try {
            j.write("C:\\Users\\Andrés F\\Desktop\\doc.docx", textPane.getDocument());
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        }
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        
         XWPFDocument doc = new XWPFDocument();
        XWPFParagraph p = doc.createParagraph();
        XWPFRun xwpfRun = p.createRun();
        
        int format=XWPFDocument.PICTURE_TYPE_JPEG;
          String imgFile;
          imgFile="C:\\Users\\Andrés F\\Pictures\\Costum-Dining-Room-Wall-Stickers.jpg";
            xwpfRun.setText(imgFile);
            xwpfRun.addBreak();
        try {
            xwpfRun.addPicture (new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels
        } catch (InvalidFormatException ex) {
            Exceptions.printStackTrace(ex);
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
          
            
    }//GEN-LAST:event_jButton2ActionPerformed

    
    private void SetFonts()
    {
        
      GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
      String[] font = env.getAvailableFontFamilyNames();      
      namesFont.setModel(new javax.swing.DefaultComboBoxModel(font));    
    
    }
    
     private void SetSizeFonts()
    {      
      String[] size = {"8","9","10","11","12","14","16","18","20","22","24","26","28","30","48","60","72"};      
      sizeFont.setModel(new javax.swing.DefaultComboBoxModel(size));
      sizeFont.setEditable(true);
    }
    
     private void listener()
     {
        textPane=styleable.getTextPanel(); 
         listenerBuscar();
         textPane.addCaretListener(new CaretListener(){

            @Override
            public void caretUpdate(CaretEvent e) {
               
                    String name=styleable.getFont();
                    int size=styleable.getFontSize();   
                    bandera=false; 
                    namesFont.setSelectedItem(name);
                    sizeFont.setSelectedItem(Integer.toString(size));
            }
        });       
     }
        
     
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField Buscar;
    private javax.swing.JLabel estado;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox namesFont;
    private javax.swing.JComboBox sizeFont;
    // End of variables declaration//GEN-END:variables
    
    
    @Override
    public void componentOpened() {
        result = Utilities.actionsGlobalContext().lookupResult(DataObject.class);
        resultStyle = Utilities.actionsGlobalContext().lookupResult(Styleable.class);
        result.addLookupListener (this);
        resultStyle.addLookupListener(this);
        
    }

    @Override
    public void componentClosed() {       
        result.removeLookupListener(this);
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

     @Override
    public void resultChanged(LookupEvent le) {
        Collection<? extends DataObject> allEvents = result.allInstances();
        Collection<? extends Styleable> allEventsStyle = resultStyle.allInstances();
        if (!allEvents.isEmpty()) {
            DataObject event = allEvents.iterator().next();            
            Dobj = event;
                if(!allEventsStyle.isEmpty()){
                    System.out.println("Styleable no está vacio");
                    styleable = allEventsStyle.iterator().next();
                    listener();
                }
            
        } else {
            System.out.println("--");
        }
    }
}
